// Express.js API服务器主入口
import express from 'express'
import cors from 'cors'
import helmet from 'helmet'
import compression from 'compression'
import rateLimit from 'express-rate-limit'
import dotenv from 'dotenv'

import { errorHandler } from './middleware/error-handler'
import { authRoutes } from './routes/auth'
import { userRoutes } from './routes/user'
import { bookmarkRoutes } from './routes/bookmarks'
import { prisma } from './lib/prisma'
import { memoryCacheManager } from './lib/memory-cache'

// 加载环境变量
dotenv.config()

const app = express()
const PORT = process.env.PORT || 3001

// 安全中间件
app.use(helmet())

// CORS配置
app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:3000',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

// 压缩响应
app.use(compression())

// 请求体解析
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true, limit: '10mb' }))

// 请求限流
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 1000, // 限制每个IP 15分钟内最多1000个请求
  message: {
    error: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
})
app.use('/api', limiter)

// 健康检查
app.get('/health', async (req, res) => {
  try {
    // 检查数据库连接
    await prisma.$queryRaw`SELECT 1`
    
    // 检查内存缓存
    await memoryCacheManager.ping()
    const cacheStats = memoryCacheManager.getStats()
    
    res.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      message: 'MySQL后端服务运行正常（内存缓存版本）',
      services: {
        database: 'connected',
        cache: {
          type: 'memory',
          status: 'connected',
          size: cacheStats.size,
          maxSize: cacheStats.maxSize
        }
      }
    })
  } catch (error) {
    res.status(503).json({
      status: 'unhealthy',
      timestamp: new Date().toISOString(),
      error: error instanceof Error ? error.message : 'Unknown error'
    })
  }
})

// API路由
app.use('/api/auth', authRoutes)
app.use('/api/user', userRoutes)
app.use('/api/bookmarks', bookmarkRoutes)

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: '接口不存在',
    path: req.originalUrl
  })
})

// 全局错误处理
app.use(errorHandler)

// 优雅关闭处理
process.on('SIGTERM', async () => {
  console.log('收到SIGTERM信号，开始优雅关闭...')
  
  // 关闭数据库连接
  await prisma.$disconnect()
  
  // 清理内存缓存
  memoryCacheManager.destroy()
  
  process.exit(0)
})

process.on('SIGINT', async () => {
  console.log('收到SIGINT信号，开始优雅关闭...')
  
  await prisma.$disconnect()
  memoryCacheManager.destroy()
  
  process.exit(0)
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 API服务器启动成功！`)
  console.log(`📍 服务地址: http://localhost:${PORT}`)
  console.log(`🏥 健康检查: http://localhost:${PORT}/health`)
  console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`)
})

export default app